/**
 * 链接提取工具类
 * 用于从网页DOM中提取导航链接
 * 支持基于语义化标签、CSS类和位置特征进行识别
 */
import { logger } from './logger';

export interface NavigationLink {
  url: string;
  text: string;
  isActive?: boolean;
  parent?: string | null;
}

export class LinkExtractor {
  /**
   * 提取页面中的导航链接
   * 基于多种选择器识别导航元素
   * @returns 提取的链接数组
   */
  static extractNavigationLinks(): NavigationLink[] {
    logger.info("开始提取页面导航链接");
    
    // 识别导航元素的选择器
    const navSelectors = [
      'nav', 'header nav', '.navigation', '.menu', '#main-menu',
      '[role="navigation"]', '.navbar', '.nav-links', '.nav'
    ];
    
    let navElements: Element[] = [];
    navSelectors.forEach(selector => {
      const elements = document.querySelectorAll(selector);
      if (elements.length > 0) {
        logger.debug(`使用选择器 ${selector} 找到 ${elements.length} 个元素`);
        navElements = [...navElements, ...Array.from(elements)];
      }
    });
    
    // 去重，防止重复处理同一元素
    navElements = Array.from(new Set(navElements));
    
    // 提取链接
    const links: NavigationLink[] = [];
    navElements.forEach(nav => {
      const anchors = nav.querySelectorAll('a');
      anchors.forEach(a => {
        logger.debug(`处理链接元素`, a);
        if (a.href && a.textContent?.trim()) {
          links.push({
            url: a.href,
            text: a.textContent.trim(),
            isActive: a.classList.contains('active') || a.getAttribute('aria-current') === 'page',
            parent: this.getParentMenuText(a)
          });
        }
      });
    });
    
    logger.info(`成功提取 ${links.length} 个导航链接`);
    return links;
  }

  /**
   * 从特定元素中提取链接
   * @param element 要提取链接的元素
   * @returns 提取的链接数组
   */
  static extractLinksFromElement(element: Element): NavigationLink[] {
    logger.debug("从选中元素提取链接");
    const links: NavigationLink[] = [];
    const anchors = element.querySelectorAll('a');
    
    anchors.forEach(a => {
      if (a.href && a.textContent?.trim()) {
        links.push({
          url: a.href,
          text: a.textContent.trim(),
          isActive: a.classList.contains('active') || a.getAttribute('aria-current') === 'page',
          parent: this.getParentMenuText(a)
        });
      }
    });
    
    logger.info(`从选中元素提取了 ${links.length} 个链接`);
    return links;
  }

  /**
   * 获取父级菜单文本
   * @param element 要查找父级菜单的元素
   * @returns 父级菜单文本或null
   */
  private static getParentMenuText(element: Element): string | null {
    // 查找父级菜单项
    let parent = element.closest('li');
    if (parent && parent.parentElement) {
      parent = parent.parentElement.closest('li');
      if (parent) {
        const parentLink = parent.querySelector('a');
        if (parentLink) {
          return parentLink.textContent?.trim() || null;
        }
      }
    }
    return null;
  }
} 